<template>
  <div class="app-container">
    <el-form :model="queryForm" ref="queryFormRef" :inline="true">
      <el-form-item props="dictName" label="字典名称">
        <el-input v-model="queryForm.dictName" placeholder="请输入字典名称" @press-enter="handleQuery" />
      </el-form-item>
      <el-form-item props="dictType" label="字典类型">
        <el-input v-model="queryForm.dictType" placeholder="请输入字典类型" @press-enter="handleQuery" />
      </el-form-item>
      <el-form-item props="status" label="状态">
        <el-select v-model="queryForm.status" placeholder="请选择字典状态">
          <el-option :value="2" label="正常" />
          <el-option :value="1" label="停用" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-space>
          <el-button v-has="'admin:sysDictType:query'" type="primary" @click="handleQuery" icon="Search">
            搜索</el-button>
          <el-button v-has="'admin:sysDictType:query'" @click="handleResetQuery" icon="Refresh"> 重置</el-button>
        </el-space>
      </el-form-item>
    </el-form>

    <el-divider />

    <div class="action">
      <el-space>
        <el-button v-has="'admin:sysDictType:add'" type="primary" @click="handleAdd" icon="Plus">新增</el-button>
        <el-button v-has="'system:sysdicttype:remove'" type="primary" status="danger" icon="Delete" @click="
            () => {
              deleteVisible = true;
            }
          "> 批量删除</el-button>
        <el-button type="primary" status="warning" disabled icon="Download"> 导出</el-button>
      </el-space>
    </div>

    <el-table v-model:data="tableData">
      <el-table-column label="编号" prop="id"></el-table-column>
      <el-table-column label="字典名称" prop="dictName"></el-table-column>
      <el-table-column label="字典类型" prop="dictType">
        <template #default="scope">
          <router-link :to="`/admin/dict/data/${scope.row.dictType}`">{{ scope.row.dictType }}</router-link>
        </template>

      </el-table-column>
      <el-table-column label="字典状态" prop="status">
        <template #default="scope">
          <el-tag v-if="scope.row.status == 2" type="success">正常</el-tag>
          <el-tag v-else type="danger">停用</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="备注" prop="remark"></el-table-column>
      <el-table-column label="创建时间" prop="createdAt">
        <template #default="scope">
          {{ parseTime(scope.row.createdAt) }}
        </template>
      </el-table-column>
      <el-table-column label="操作" prop="action"></el-table-column>
    </el-table>

    <el-pagination :page-size="10" v-model="currentPage" layout="prev, pager, next" :total="pager.count"
      @current-change="handlePageChange" />

    <!-- Modal弹框 -->
    <el-dialog v-model="modalVisible" title-align="start" :title="modalTitle" @before-ok="handleSubmit"
      @close="modalFormRef.resetFields()">
      <el-form v-model="modalForm" ref="modalFormRef">
        <el-form-item prop="dictName" label="字典名称">
          <el-input v-model="modalForm.dictName" placeholder="请输入字典名称" :disabled="modalForm.id ? true : false"></el-input>
        </el-form-item>
        <el-form-item prop="dictType" label="字典类型">
          <el-input v-model="modalForm.dictType" placeholder="请输入字典类型" :disabled="modalForm.id ? true : false"></el-input>
        </el-form-item>
        <el-form-item prop="status" label="状态">
          <el-radio-group v-model="modalForm.status">
            <el-radio :label="2">正常</el-radio>
            <el-radio :label="1">停用</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item prop="remark" label="备注">
          <el-input v-model="modalForm.remark" placeholder="请输入内容备注" type="textarea"></el-input>
        </el-form-item>
      </el-form>
    </el-dialog>

    <!-- Akiraka 20230223 删除与批量删除 开始 -->
    <DeleteModal :data="deleteData" :visible="deleteVisible" :apiDelete="removeDictType"
      @deleteVisibleChange="() => (deleteVisible = false)" />
    <!-- Akiraka 20230223 删除与批量删除 结束 -->
  </div>
</template>

<script setup>
import {
  reactive,
  ref,
  getCurrentInstance,
  nextTick,
  onMounted,
  watch,
} from "vue";

import {
  getDictType,
  addDictType,
  removeDictType,
  updateDictType,
} from "@/api/admin/sys-dict";
import { parseTime } from '@/utils/parseTime';
import PageTable from "@/components/Table/PageTable.vue";

// Akiraka 20230210 删除数据
const deleteData = ref([]);
// Akiraka 20230210 删除对话框
const deleteVisible = ref(false);
// Akiraka 20230210 监听删除事件
watch(
  () => deleteVisible.value,
  (value) => {
    if (value == false) {
      getSysDictTypeInfo({ ...pager, ...queryForm });
    }
  }
);

const { proxy } = getCurrentInstance();

const currentPage = ref(1);

// pager
const pager = {
  count: 0,
  pageIndex: 1,
  pageSize: 10,
};

// form
const modalForm = reactive({
  status: 2,
});

// Table
const tableData = ref([]);
const tableColumns = [
  { title: "编号", dataIndex: "id" },
  { title: "字典名称", dataIndex: "dictName" },
  { title: "字典类型", dataIndex: "dictType", slotName: "dictType" },
  { title: "字典状态", dataIndex: "status", slotName: "status" },
  { title: "备注", dataIndex: "remark" },
  { title: "创建时间", dataIndex: "createdAt", slotName: "createdAt" },
  { title: "操作", slotName: "action" },
];

// Modal
const modalVisible = ref(false);
const modalTitle = ref("默认标题");
const queryFormRef = ref(null);
const modalFormRef = ref(null);
const { queryForm, handleQuery, handleResetQuery } = useQueryDict();
// 搜索
function useQueryDict() {
  const queryForm = reactive({});

  const handleQuery = () => {
    getSysDictTypeInfo(queryForm);
  };

  const handleResetQuery = () => {
    queryFormRef.value.resetFields();

    currentPage.value = 1;
    getSysDictTypeInfo(queryForm);
  };

  return {
    queryForm,
    handleQuery,
    handleResetQuery,
  };
}

// 页码改变
const handlePageChange = (page) => {
  console.log("handlePageChange")
  pager.pageIndex = page;
  currentPage.value = page;

  getSysDictTypeInfo({ ...pager, ...queryForm });
};

// 每页数据量改变
const handlePageSizeChange = (pageSize) => {
  pager.pageSize = pageSize;

  getSysDictTypeInfo({ ...pager, ...queryForm });
};

// 新增
const handleAdd = () => {
  modalVisible.value = true;
  modalTitle.value = "新增字典";
};

// 修改
const handleUpdate = async (record) => {
  modalVisible.value = true;
  modalTitle.value = "修改字典";

  await nextTick();
  Object.assign(modalForm, record);
};

// Submit
const handleSubmit = (done) => {
  modalFormRef.value.validate(async (err) => {
    if (!err) {
      try {
        let res;
        if (Reflect.has(modalForm, "id")) {
          const { code, msg } = await updateDictType(modalForm, modalForm.id);
          if (code == 200) {
            proxy.$message.success("更新成功");
          } else {
            proxy.$message.error(msg);
          }
        } else {
          const { code, msg } = await addDictType(modalForm);
          currentPage.value = Math.ceil(++pager.count / pager.pageSize);
          pager.pageIndex = currentPage.value;
          if (code == 200) {
            proxy.$message.success("新增成功");
          } else {
            proxy.$message.error(msg);
          }
        }
        modalVisible.value = false;
        getSysDictTypeInfo(pager);
        done();
      } catch (e) {
        done(false);
      }
    } else {
      proxy.$message.error("表单校验失败！");
      done(false);
    }
  });
};

// 获取字典数据
const getSysDictTypeInfo = async (params = {}) => {
  const { data, code, msg } = await getDictType(params);
  console.log(data);
  if (code == 200) {
    tableData.value = data.list;
    Object.assign(pager, {
      count: data.count,
      pageIndex: data.pageIndex,
      pageSize: data.pageSize,
    });
  } else {
    proxy.$message.error(msg);
  }
};

onMounted(async () => {
  getSysDictTypeInfo();
});
</script>

<style lang="scss">
.action {
  margin-bottom: 12px;
}
</style>
